package com.qidian.buy.sso.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qidian.buy.entity.User;
import com.qidian.buy.sso.mapper.UserMapper;
import com.qidian.buy.sso.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qidian.buy.util.JSONTools;
import com.qidian.buy.util.pojo.BuyResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 戴着假发的程序员
 * @since 2023-05-18
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public BuyResult saveUser(User user) {
        // 校验用户名是否重复
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",user.getUsername());
        List<User> users = userMapper.selectList(wrapper);
        if(users != null && users.size() > 0){
            return BuyResult.fal("用户名重复");
        }
        // 对密码进行加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        //补全数据
        user.setCreated(new Date());
        user.setUpdated(new Date());
        // 直接保存
        return userMapper.insert(user)==1?BuyResult.ok(user):BuyResult.fal();
    }

    @Override
    public BuyResult login(String username, String password) {
        // 完成登录操作
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User user = userMapper.selectOne(wrapper);
        //  对密码加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (user != null && user.getPassword().equals(password)){
            // 登录成功
            // 产生一个token
            String token = UUID.randomUUID().toString().replace("-","");
            String key = "SESSION_"+token;
            // 将用户信息转换为json存储到redis中
            redisTemplate.opsForValue().set(key, JSONTools.object2json(user));
            // 设置key的时间
            redisTemplate.expire(key,30, TimeUnit.MINUTES);
            // 返回
            return BuyResult.ok(token);
        }

        return BuyResult.fal();
    }

    @Override
    public BuyResult<User> checkLogin(String token) {
        String key = "SESSION_" + token;
        //  判断key是否存在
        if(redisTemplate.hasKey(key)){
            String userJosn = redisTemplate.opsForValue().get(key);
            try {
                User user = JSONTools.json2object(userJosn,User.class);
                //  重新定义key的时间
                redisTemplate.expire(key,30, TimeUnit.MINUTES);
                return BuyResult.ok(user);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return BuyResult.fal();
    }
}
